package com.shanghaionstar.notification.service;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.telephony.TelephonyManager;

import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;

import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.publicService.DeviceInfoEntity;
import com.onstar.cn.mag.publicService.SessionEntity;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.shanghaionstar.notification.bean.NotificationConstants;
import com.shanghaionstar.notification.service.impl.InterfaceServiceImpl;
import com.shanghaionstar.utils.BusinessUtil;
import com.tencent.android.tpush.XGPushConfig;

import java.util.ArrayList;
import java.util.List;

public class NotificationControl  {
	private static NotificationControl controll;
	private Context context;
	private InterfaceService service;
	private RequestParams params;

	/**
	 * provide result handler for the invoker
	 */
	private Handler handler;

	public static NotificationControl getInstants(Context ctx){
		if(controll==null){
			controll=new NotificationControl(ctx);
		}
		return controll;
	}
	public static NotificationControl getInstants(Context ctx, Handler handler){
		if(controll==null){
			controll=new NotificationControl(ctx);
		}
		return controll;
	}

	private NotificationControl(Context context) {
		this.context = context.getApplicationContext();
		service = new InterfaceServiceImpl(context, Constants.CURRENT_SERVER_URL);
	}

	private NotificationControl(Context context, Handler handler) {
		this.context = context.getApplicationContext();
		service = new InterfaceServiceImpl(context,Constants.CURRENT_SERVER_URL);
		this.handler = handler;
	}

	public void startNotification() {
		Intent intent = new Intent(context, NotificationService.class);
		intent.putExtra("params", params);
		context.startService(intent);
	}

	public void setParams(RequestParams params) {
		this.params = params;
	}
	public RequestParams getParams() {
		return params;
	}

	public void stopNotification() {
		service.disconnect();
	}

	public void saveSessionAfterLogin(final SessionEntity sessionEntity) {
		SessionEntity sendReq = createSessionEntity(sessionEntity);
		service.saveSession(sendReq, new ResponseHandler() {
			@Override
			public void onSuccess(String tag, String json) {
				String code = GsonHelper.getObjectValue(json, "code");
				if(handler != null) {
					if(ErrorEnum.E0000.getStringValue().equals(code)) {
						handler.sendEmptyMessage(NotificationConstants.SUCCESS);
					}else {
						handler.sendEmptyMessage(NotificationConstants.FAIL);
					}
				}
			}

			@Override
			public void onError(String tag, HttpException e) {
				if(handler != null) {
					handler.sendEmptyMessage(NotificationConstants.FAIL);
				}
			}
		});
	}


	/**
	 * @param sessionEntity
	 * @return
	 */
	private SessionEntity createSessionEntity(SessionEntity sessionEntity) {
		SessionEntity sendReq = new SessionEntity();
		DeviceUtil deviceUtil = new DeviceUtil(context);
		String deviceId = new DeviceUtil(context).getDeviceID();
		sendReq.setDeviceID(deviceId);
		sendReq.setImsi(deviceUtil.getIMSI());
		sendReq.setUserID(sessionEntity.getUserID());
		sendReq.setDeviceType(NotificationConstants.DEVICETYPE);
//		sendReq.setDeviceToken(NotificationConstants.DEVICETYPE);
		sendReq.setDeviceToken(XGPushConfig.getToken(context));
		sendReq.setIsNotification("Y");
		sendReq.setIsAlert("Y");
		sendReq.setIsBind("Y");
		sendReq.setChannelID(NotificationConstants.CHANNEL_ID);
		sendReq.setEmail(sessionEntity.getEmail());
		sendReq.setMobileNumber(sessionEntity.getMobileNumber());
		sendReq.setSubscriberID(sessionEntity.getSubscriberID());
		sendReq.setUserName(sessionEntity.getUserName());
		sendReq.setRole(sessionEntity.getRole());
		if(!CommonUtil.isNull(sessionEntity.getVehicles())){
			List<Vehicle> tmpVehicles = new ArrayList<Vehicle>();
			for(Vehicle vehicle : sessionEntity.getVehicles()) {
				Vehicle tmpVehicle = new Vehicle();
				tmpVehicle.setVin(vehicle.getVin());
				tmpVehicle.setYear(vehicle.getYear());
				tmpVehicle.setAccountID(sessionEntity.getAccountID());
				tmpVehicle.setMake(vehicle.getMake());
				tmpVehicle.setModel(vehicle.getModel());
				tmpVehicle.setModelDesc(vehicle.getModelDesc());
				tmpVehicle.setMakeDesc(vehicle.getMakeDesc());
				tmpVehicles.add(tmpVehicle);
			}
			sendReq.setVehicles(tmpVehicles);
		}
		return sendReq;
	}

	public void saveDeviceInfo(boolean isLogin) {
		DeviceInfoEntity req = createSaveDeiveRequest(isLogin);
		service.saveDeviceInfo(req, new ResponseHandler() {
			@Override
			public void onSuccess(String tag, String json) {
				String code = GsonHelper.getObjectValue(json, "code");
				if(handler != null) {
					if(ErrorEnum.E0000.getStringValue().equals(code)) {
						handler.sendEmptyMessage(NotificationConstants.SUCCESS);
					}else {
						handler.sendEmptyMessage(NotificationConstants.FAIL);
					}
				}
			}
			@Override
			public void onError(String tag, HttpException e) {
				if(handler != null) {
					handler.sendEmptyMessage(NotificationConstants.FAIL);
				}
			}
		});
	}

	private DeviceInfoEntity createSaveDeiveRequest(boolean isLogin) {
		DeviceInfoEntity req = new DeviceInfoEntity();
		try{
			String deviceId = new DeviceUtil(context).getDeviceID();
			req.setDeviceID(deviceId);
			req.setDeviceOS(NotificationConstants.DEVICE_OS);
			req.setDeviceToken(XGPushConfig.getToken(context));
			req.setDeviceType(NotificationConstants.DEVICETYPE);
			req.setIsAlert("Y");
			req.setIsNotification("Y");
			if(isLogin){
				req.setIsBind("Y");
			}else {
				req.setIsBind("N");
			}
		}catch (Exception e) {
			LogManager.getInstance().e(e.getMessage());
		}
		return req;
	}
}
